import React, { Component } from "react"
import ReactDOM from "react-dom"
import stores from "./stores"
import { Provider,observer,inject } from 'mobx-react'

import PhoneToastr from './../../library/components/phone_toastr/index'

import I18nProvider from './../../library/components/i18n_provider/index'

import * as config from './../../../config/index'

import './index.scss'
import * as tools from "../../library/tools"

// 门店gps
@inject('pageinitStore')
@inject('shopGpsStore')
@observer
class ShopGpsWrap extends Component {
    constructor(props) {
        super(props)

        this.map // 地图对象
        this.position = {
            lng: 0, // 经度
            lat: 0, // 纬度
        }

        this.markerList = [] // 标准数据

        this.serachInput = React.createRef()

        let lang = ShopGpsWrap.getTransitionLan(tools.getUrlParam('lang') || 'zh')

        props.pageinitStore.setI18nMessagesInfoHandle(( lang.indexOf('zh') >= 0 ? 'zh':'en' ))
    }
    static getTransitionLan(lan) {
        switch (lan) {
            case 'zh-Hans':
                return 'zh'
            default:
                return 'en'
        }
    }
    componentDidMount() {
        // 添加地图
        const gaodeMapsDom = document.createElement('script')
        const headerDom = document.querySelector('head')

        gaodeMapsDom.type = 'text/javascript'
        gaodeMapsDom.src = `https://webapi.amap.com/maps?v=1.4.2&key=${config.gaode_map_key}&plugin=AMap.Geocoder&callback=init`

        window.init = () => {
            this.map = new AMap.Map('container', {
                resizeEnable: true
            })
            this.getUserLocation()
        }
        headerDom.appendChild(gaodeMapsDom)
    }
    // 获取用户地址位置
    getUserLocation() {
        let geolocation

        this.map.plugin('AMap.Geolocation', () => {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition:'RB'
            })
            this.map.addControl(geolocation)
            geolocation.getCurrentPosition()
            //解析定位结果
            AMap.event.addListener(geolocation, 'complete', (data) => {
                this.position = {
                    lng: data.position.getLng(),
                    lat: data.position.getLat(),
                }
                this.serachShopListFunc()
            });
            // 定位错误
            AMap.event.addListener(geolocation, 'error', (data) => {
                new PhoneToastr().error('定位失败')
                this.serachShopListFunc()
            })
        });
    }
    // 设置标注
    setLocalMarker() {
        this.map.remove(this.markerList)
        this.markerList = []

        this.props.shopGpsStore.shopGpsList.map(item => {
            this.markerList.push(new AMap.Marker({
                position: new AMap.LngLat(item.lng, item.lat),
                offset: new AMap.Pixel(-10, -10),
                icon: '', // 添加 Icon 图标 URL
                title: item.shopName
            }))
        })

        this.map.add(this.markerList);
    }
    serachShopListFunc() {
        let json = {}

        if (this.position.lng) {
            json = {
                shopName: this.serachInput.current.value,
                lon: this.position.lng,
                lat: this.position.lat,
            }
        } else {
            json = {
                shopName: this.serachInput.current.value,
            }
        }
        this.props.shopGpsStore.sendCommonShopListReqeust(json, this.setLocalMarker.bind(this))
    }
    // 改变地图视图
    changeMapLngLatHandle(lng, lat) {
        this.map.panTo([lng,lat])
    }
    // 处理本地到店的距离
    getDistanceFiltr(val) {
        if (!val) {
            return `0米`
        }

        if(val <= 1000) {
            return `${val}米`
        } else {
            return `${(val / 1000).toFixed(2)}公里`
        }
    }
    gotoMapApp(lng, lat) {
        window.location.href = `https://uri.amap.com/marker?position=${lat},${lng}`
    }
    render() {
        let lang = this.props.pageinitStore.intl.locale

        return <div className="shopgps-wrap">
            <div className="shopgps-header">
                <div className="shopgps-header-left">
                    取消
                </div>
                <div className="shopgps-header-input">
                    <div className="input-icon"></div>
                    <input type="text" ref={this.serachInput} className={'input-text'}/>
                </div>
                <div className="shopgps-header-right" onClick={this.serachShopListFunc.bind(this)}>搜索</div>
            </div>
            <div className="shopgps-map" id={'container'}>
            </div>
            <div className="shopgps-list">
                {this.props.shopGpsStore.shopGpsList.map((item, index) => {
                    if ([13, 100, 99].indexOf(item.id) > -1) {
                        return null
                    }
                    return <div className="shopgps-list-item" key={index} onClick={() => {this.changeMapLngLatHandle(item.lng,item.lat)}}>
                        <div className="list-item-info">
                            <div className="list-item-info-img" >
                                <div style={{backgroundImage: `url(${config.node_oss_path + item.shopImg})`}}></div>
                            </div>
                            <div className="list-item-info-basic">
                                <div className="basic-title">
                                    <span className={'info'}>{item.shopName}</span>
                                </div>
                                {/*<div className="basic-evaluate">*/}
                                {/*<div className="basic-evaluate-chunk">*/}
                                {/*<div className="chunk-item"></div>*/}
                                {/*<div className="chunk-item"></div>*/}
                                {/*<div className="chunk-item"></div>*/}
                                {/*<div className="chunk-item"></div>*/}
                                {/*<div className="chunk-item"></div>*/}
                                {/*</div>*/}
                                {/*<div className="basic-evaluate-info">*/}
                                {/*<span>4545</span>人去过*/}
                                {/*</div>*/}
                                {/*</div>*/}
                                <div className="basic-lable">
                                    {item.distance?<div className="basic-lable-item">{this.getDistanceFiltr(item.distance)}</div>:null}
                                    <div className="basic-lable-item">智能无人便利店</div>
                                </div>
                                <div className="basic-info">{item.address}</div>
                            </div>
                            <div className="list-item-info-path" onClick={()=> {this.gotoMapApp(item.lng, item.lat)}}>
                                <div className="path-img"></div>
                                <div className="path-title">路线</div>
                            </div>
                        </div>
                    </div>
                })}
            </div>
        </div>
    }
}

ReactDOM.render(<Provider {...stores}>
        <I18nProvider>
            <ShopGpsWrap/>
        </I18nProvider>
    </Provider>,document.getElementById('istore-app'))